<template>
    <div class="wrap">
        <!--信息头-->
        <span>发布商品</span>
        <el-divider></el-divider>
        <!-- 要带上用户/企业id给 -->
        <div class="banner">
            <el-card class="card_class">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" label-position="top">
                    <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeLeave">
                        <el-tab-pane label="基本信息" name="0">
                            <el-form-item label="商品名称" prop="goodsSkuName">
                                <el-input v-model="ruleForm.goodsSkuName" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="商品分类" prop="goodsTypeId">
                                <el-select v-model="ruleForm.goodsTypeId" placeholder="请选择商品大类" @change="onTypeChange">
                                    <el-option label="铝土矿" value="1"></el-option>
                                    <el-option label="氧化铝" value="2"></el-option>
                                    <el-option label="电解铝" value="3"></el-option>
                                    <el-option label="成品铝" value="4"></el-option>
                                </el-select>
                            </el-form-item>
                            <!-- <el-form-item>
                                <el-option v-for="(spu,index) in spuList" :key="index" :label="index" :value="spu"></el-option>                        
                            </el-form-item> -->
                            <!-- 种类占据1个slot -->
                            <!-- 其他20个slot里头任填写 -->
                            <!-- slot1 slot2 slot3 slot4 -- {"长":slot1,"高":slot2,"宽":slot}>


                            <一个sku规格> 1-1 <user> 可以作为历史选择
                                "填了的slot的key name以及数量" (keyname,quality)->前端读取并显示排列
                            二、根据json还原格式 + 正确构成crud


                            <!不允许发布绑定企业之外的其他企业的商品 -->
                            <!-- <el-form-item label="企业名字" prop="fname">
                                <el-input v-model="ruleForm.name"></el-input>
                            </el-form-item> -->
                             <el-form-item label="商品描述" prop="goodsSkuDesc">
                                <el-input v-model="ruleForm.goodsSkuDesc" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="预期价格(元/千克)" prop="goodSsku_price">
                                <el-input v-model="ruleForm.goodsSkuPrice" type="number"  @keydown.native="inputLimit"></el-input>
                            </el-form-item>
                            <el-form-item label="商品图像">
                                <el-upload
                                        class="avatar-uploader"
                                        action="http://ip:port/file/upload"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                        :before-upload="beforeAvatarUpload"
                                        :http-request="uploadFile">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-tab-pane>
                        <!-- 需要 -->
                        <el-tab-pane label="商品参数" name="1">
                            <!-- 需要设置规格参数 -->
                            <div class="demo-input-suffix" v-for="i in 7" :key="i">
                                <div style="margin: 20px 10px">参数{{i}}</div>
                                <div style="margin: 10px 5px">
                                    <el-input
                                        placeholder="请输入参数名字，例:长"
                                        v-model="specNameList[i]">
                                    </el-input>
                                </div>
                                <div style="margin: 10px 10px 5px 2px">
                                    <el-input
                                        placeholder="请输入参数取值，例:10cm"
                                        v-model="specValueList[i]">
                                    </el-input>
                                </div>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="联系方式" name="2">
                            <el-form-item label="联系电话" prop="firmPhone">
                                <el-input v-model="ruleForm.firm_phone" type="number"  @keydown.native="inputLimit"></el-input>
                            </el-form-item>
                            <el-form-item label="联系邮箱" prop="firmMail">
                                <el-input v-model="ruleForm.firm_mail"></el-input>
                            </el-form-item>
                            <el-form-item align="right">
                                <el-button type="primary" @click="add">发布</el-button>
                                <el-button>取消</el-button>
                            </el-form-item>
                        </el-tab-pane>
                    </el-tabs>

                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script>
import axios from "@/utils/request"
export default {
    data() {
        return {
            imageUrl: '',
            ruleForm: {
                goodsSkuName: '',
                goodsSkuId: '',
                // 后端自动生成日期，这里不用填
                goodsTypeId: '',
                goodsSkuDesc: '',   
                // cols:["1","2","3"],
                goodsSkuSpec:"",
                imageUrl:'',
            },
            activeIndex:"0",
            selected:false,
            goodsSpecList: {"1":["含铝量","铝硅比"],
                            "2":["含铝量","铝硅比"],
                            "3":["长","宽","高"],
                            "4":["长","宽","高"],
                            "5":["长","宽","高"],
                            "6":["长","宽","高"],
                            "7":["平均粒度"],
                            "8":["长","宽","高"],
                            "9":["长","宽","高"],
            },
            goodSspec:["参数1","参数2","参数3"],//属性名
            specNameList:["","","","","","",""],
            specValueList:["","","","","","",""],
            
            rules: {
                goodsSkuName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { max: 10, message: '长度在10个字符以下', trigger: 'blur' }
                ],
                goodsSkuId: [
                    { required: true, message: '请选择商品大类', trigger: 'change' }
                ],
                firm_email:[
                    {
                        required: false,
                        pattern:/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: '请输入正确的邮箱',
                        trigger: 'blur'
                   }
                ],
                // goodsSpuId: [
                //     { required: true, message: '请选择商品种类', trigger: 'change' }
                // ],
            },
            sampleData:[],
            spuList:[],
            testList:{"1":[{"goodsSpuId":1,"goodsSpuName":"古风化壳矿土",},{"goodsSpuId":2,"goodsSpuName":"红土"}],
                      "2":[{"goodsSpuId":7,"goodsSpuName":"α型氧化铝",}],
                      "3":[{"goodsSpuId":4,"goodsSpuName":"AC4D",},{"goodsSpuId":5,"goodsSpuName":"AC5A"},{"goodsSpuId":6,"goodsSpuName":"A308"}],
                      "4":[{"goodsSpuId":8,"goodsSpuName":"铝条",},{"goodsSpuId":9,"goodsSpuName":"铝板",}]
            },
            postFormUrl:"http://localhost:8009/lv-industry-app/goodsSku/create",
            postImgUrl:"http://${ip}:${port}/{{context}}/file/upload",
            getUrl2:"http://localhost:8009/lv-industry-app/goodsSpu/get-spu/",
            getUrl:"http://localhost:8009/lv-industry-app/goodsSpu/get-spec-name/",
        };
    },
    methods: {
        onTypeChange()
        {
            console.log(this.ruleForm.goodsTypeId)

            // this.spuList = this.getSpuList()
            this.ruleForm.goodsSpuId = ''
            this.spuList = this.testList[this.ruleForm.goodsTypeId]
            
            console.log(this.spuList)

        },
        onSpuChange()
        {
            // this.goodSspec = this.getSpecName()
            this.goodsSpec = this.goodsSpecList[this.ruleForm.goodSpuId]
            console.log(this.ruleForm.goodsSpuId)
            // console.log(this.goodsSspec)
        },
        inputLimit(e)
        {
            let key = e.key
            if(key === 'e' || key === '.')
            {
                this.$message.error("只能输入数字！")
                e.returnValue = false
                return false
            }
            return true
        },
        async getSpuList()
        {
            await axios.get(this.getUrl + this.ruleForm.goodsTypeId).then(function(result){
                this.spuList = result.data  //列表
            })
        },
        async uploadFile(f)
        {
            let src = "goods/test"
            let data = new FormData()
            data.append('file',f)
            let offset = {}
            offset.metadata = {}
            offset.data = data
            offset.theme = src
            let config = {"headers":{"Content-Type":"multipart/form-data"}}
            this.axios.post(postImgUrl,offset,config).then((result)=>{
                if(result.success == true)
                {
                    console.log("Success!")
                    this.ruleForm.imageUrl = "http://${ip}:{port}/" + result.data
                }
            })
        },
        async getSpecName()
        {
            
            this.goodsSspec = []
            this.cols = []
            await axios.get(this.getUrl2 + this.ruleForm.goodsSpuId).then((result)=>{
                //如果这里仍是字符串则需要转为json
                //否则如果是json格式直接将key都放[](goodSspec)里面去
                for(var i in result.data)
                {
                    this.goodSspec.push(i)
                    this.cols.push(i)
                }
            })
        },
        beforeLeave(activeName,oldActiveName)
        {
            if(oldActiveName === "0" && this.ruleForm.goodsTypeId === "")
            {
                this.$message.error("需要选定商品种类")
                console.log(activeName)
                return false
            }
            return true
        },
        add()
        {
            // this.ruleForm.validate((valid)=>{
            //     if(!valid)
            //     {
            //         return this.$message.error("请按要求填写表单")
            //     }
            // });
            //将填写的表格重写成String->不用，后端接收到了再改
            /*
                {""}
            */
        //    this.submitForm("ruleForm")
        //    this.ruleForm.packedSpec = {}
        //    for(var name in this.goodSspec)
        //    {
        //        this.ruleForm.packedSpec[name] = this.ruleForm[name]
        //    }
        //    console.log(this.ruleForm.packedSpec)
           this.$refs.ruleForm.validate((valid)=>{
                if (valid) {
                    this.$message('submit!')
                    // this.$http.post(postFormUrl,cre_para).then(function(res){console.log(res)})
                    console.log(this.ruleForm)

                } else {
                    this.$message('error submit!!')
                    return false;
                }
           })
           let tmp = {}
           for(var i = 0;i < 7;i++)
           {
               if(this.specNameList[i] !== "" && this.specValueList[i] !== "")
               {
                   tmp[this.specNameList[i]] = this.specValueList[i] //需要确保有值
               }
           }
           this.ruleForm.goodsSkuSpec = JSON.stringify(tmp)
           console.log(this.ruleForm)
           this.submitForm()
        },
        async submitForm() {
            var cre_para = {}
        
            let that = this.$router
            console.log(that)
            cre_para = JSON.stringify(this.ruleForm)
            // console.log("Here")
            // console.log(cre_para)
            await axios.post(this.postFormUrl,cre_para,{headers:{
            'Content-Type': 'application/json'
        }}).then((result)=>{
                console.log(result)
                if(result.success == true)
                {
                    alert("提交成功！")
                }
                else
                {
                    alert("提交失败，请重试！")
                }
            })
        },
        resetForm() {
            this.ruleForm.resetFields();
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(this.imageUrl)
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>

<style lang="less" scoped>
    .wrap{
        .banner{
            width: 1200px;
            height: 100%;
            .card_class{
                width: 800px;
                height: 100%;
                margin: 0 auto;
            }
        }
    }
    // 上传图片样式
    .avatar-uploader{
        width: 178px;
        height: 178px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .demo-input-suffix
    {
        display:flex;
        margin-top:10px;
        margin-bottom:10px;
        
    }

    .demo-ruleForm
    {
        margin:0 auto 
    }
</style>
